package com.lagou.web;

import com.lagou.domain.Student;
import com.lagou.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddStudentServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1. 设置编码问题
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // 2.  获取参数stdNo, stdName, stdGender, birthDate
        int stdNo = Integer.parseInt(req.getParameter("stdNo"));
        String stdName = req.getParameter("stdName");
        String stdGender = req.getParameter("stdGender");
        Date birthDate = null;
        try {
            birthDate = new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birthDate"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // System.out.println(stdNo + " " + stdName + " " + stdGender + " " + birthDate);

        // 4. 根据参数创建Student对象
        Student student = new Student(stdNo, stdName, stdGender, birthDate);
        // 5. 创建StudentService对象，调用方法实现数据插入
        StudentService service = new StudentService();
        int cnt = 0;
        try {
            cnt = service.insertStudent(student);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            resp.getWriter().write("<script> alert(学生信息添加失败！！);</script>");
        }
        // cnt -1 学号重复；0 添加失败 ； 1 添加成功
        if (-1 == cnt) {
            resp.sendRedirect("/student_management_system/add_error.html");
        } else if (1 == cnt) {
            resp.sendRedirect("/student_management_system/add_success.html");
        }
    }
}
